package com.qidianit.mes.pro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidianit.mes.pojo.Result;
import com.qidianit.mes.pojo.pro.Process;
import com.qidianit.mes.pojo.pro.WorkflowProcess;
import com.qidianit.mes.pro.mapper.DictDataMapper;
import com.qidianit.mes.pro.mapper.ProcessMapper;
import com.qidianit.mes.pro.mapper.WorkflowProcessMapper;
import com.qidianit.mes.pro.service.WorkflowProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ Description:
 * @ Author: 戴着假发的程序员
 * @ Date: 2025/9/19 - 11:15
 */
@Service
public class WorkflowProcessServiceImpl implements WorkflowProcessService {

    @Autowired
    private WorkflowProcessMapper workflowProcessMapper;
    @Autowired
    private ProcessMapper processMapper;
    @Autowired
    private DictDataMapper dictDataMapper;

    @Override
    public Result<PageInfo<WorkflowProcess>> selectList(Long workflowId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        // 查询关系对象列表
        List<WorkflowProcess> workflowProcesses = workflowProcessMapper.selectList(workflowId);
        // 遍历组织数据
        for (WorkflowProcess wp : workflowProcesses){
            // 查询当前工序
            wp.setProcess(processMapper.selectById(wp.getProcessId()));
            // 查询下一道工序
            // 查询当前工艺的所有工序 按照序号顺序排序。  根据当前工序找到当前工序的下一道工序。
            // 查询当前工序的所有工序
            List<Process> processes = processMapper.selectProcessByWorkflowId(wp.getWorkflowId());
            Process nextProcess = getNextProcess(processes, wp.getProcess());
            wp.setNextProcess(nextProcess);
            // 查询与下一道工序关系的字典信息
            wp.setRelationNextDict(dictDataMapper.selectById(wp.getRelationNext()));
        }
        return Result.success(new PageInfo<>(workflowProcesses));
    }

    /**
     *
     * @param processes
     * @param process
     * @return
     */
    private Process getNextProcess(List<Process> processes,Process process){
        // 从processes 找到 process 的下一道工序，如果没有就返回null。
        for (int i = 0 ;i < processes.size() - 1;i ++){
            if (processes.get(i).getId().equals(process.getId()) && processes.get(i + 1) != null){
                return processes.get(i + 1);
            }
        }
        return null;
    };
}
